import { qaGameApi } from "@/constants/api/qa-gameapi"
import { mainApi } from "@/constants/api/mainapi"
import { mkQaPaintCfg } from './qa-paint-cfg'
import { getShareConfig } from "@/utils/shareConfig";

const letterDict = { 0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G' }
const staticWidth = 80;
const maxTimeout = 10;
const timeoutWarn = 5;
const waitNextTime = 1000;
const scoreParse = (v = 0) => Math.ceil(v / 7.5);
const app = getApp();

Page({
  data: {
    letterDict,
    timeoutWarn,
    maxTimeout,
    circleWidth: staticWidth,
    timerCntVal: maxTimeout,
    painterInfo: {},
    circleVisible: false,
    modalVisible: false,
    paused: false,
    current: 0,
    total: 0,
    score: scoreParse(0),
    level_info: {},
    answerDict: {},
    questionList: [],
  },
  onLoad(options) {
    this.toStart()
  },
  onShareAppMessage() {
    return getShareConfig({
      realPath: '/pages/index/index',
      title: '趣味测试，老登指数，看看谁更young'
    })
  },
  toStart() {
    this.playAgain()
  },
  /**
   * @description 暂停游戏，如果计时为0，不允许暂停
   */
  toPause() {
    this.timeLeft = this.data.timerCntVal
    if (this.timeLeft === 0) return;
    this.setData({
      paused: true,
      modalVisible: true,
    })
    this.stopCount()
  },
  toResume() {
    this.setData({
      paused: false,
      modalVisible: false,
    })
    this.startCount(this.timeLeft)
  },
  playAgain() {
    this.setData({
      paused: false,
      modalVisible: false,
      current: 0,
      total: 0,
      score: scoreParse(0),
      level_info: {},
      answerDict: {},
      questionList: [],
    })
    this.getQusetions()
  },
  async getQusetions() {
    const { data } = await app.$request({
      url: qaGameApi.getQs,
      method: 'get',
    })
    console.log(data);
    this.startCount();
    this.setData({
      answerDict: {}, // 初始化答案字典对象
      current: Math.min(1, data.count),
      total: data.count,
      questionList: data.question_list
    })
  },
  refreshCircle() {
    this.setData({ circleVisible: false }, () => {
      setTimeout(() => {
        this.setData({ circleVisible: true })
      }, 5)
    })
  },
  stopCount() {
    clearInterval(this.cnttimer)
  },
  /**
   * @description 倒计时开始
   * @param {number} t 剩余时间
   */
  startCount(t = maxTimeout) {
    this.stopCount()
    this.setData({ timerCntVal: t }, () => {
      this.refreshCircle()
    })
    this.cnttimer = setInterval(() => {
      const { timerCntVal } = this.data
      const v = Math.max(timerCntVal - 1, 0)
      this.setData({ timerCntVal: v })
      if (v == 0) {
        this.stashAnswer()
      }
    }, 1000)
  },
  stashAnswer(e) {
    const { current, answerDict } = this.data;
    let optionval = '';
    this.stopCount();
    if (e) {
      optionval = e.currentTarget.dataset.optionval;
    }
    this.durationDict = { // 记录时间
      ...this.durationDict,
      [current]: maxTimeout - this.data.timerCntVal
    }
    if (answerDict[current] != undefined) { return; }
    answerDict[current] = optionval;
    console.log(answerDict, this.durationDict);

    this.setData({
      answerDict,
    })
    if (current == this.data.questionList.length) {
      this.submitRes()
    } else {
      setTimeout(() => {
        this.toNextQuestion()
      }, waitNextTime);
    }
  },
  toNextQuestion() {
    const { current, } = this.data;
    this.startCount();
    this.setData({
      current: current + 1,
    })
  },
  /**
   * @description 提交问题答案
   */
  async submitRes() {
    this.stopCount();
    const content = this.data.questionList.map((e, j) => {
      const val = this.data.answerDict[j + 1]
      return {
        "quiz_id": e.id,
        "answer": val,
        "is_correct": val === e.correct,
        "duration": this.durationDict[j + 1],
      }
    })
    // return console.log(content);
    const { data } = await app.$request({
      url: qaGameApi.getRes,
      method: 'post',
      data: {
        content
      }
    })
    this.setData({
      modalVisible: true,
      level_info: data.level_info,
      score: scoreParse(data.score),
    })
    // this.parseSubmited(data)
  },
  // /**
  //  * @description 格式化答案再提交，里面的rank-count-percent都是需要调整的值
  //  */
  // async parseSubmited(res) {
  //   const { answerDict, questionList } = this.data;
  //   let count = 0;
  //   let obj = {};
  //   questionList.forEach((e, j) => {
  //     if (e.correct == answerDict[j + 1]) {
  //       count++
  //     }
  //   })
  //   const { data } = await app.$request({
  //     url: mainApi.gtQrcode,
  //     data: {
  //       path: 'pages/index/index',
  //       scene: 'q_laodeng'
  //     }
  //   })
  //   console.log(data.img);
  //   obj = mkQaPaintCfg({
  //     count,
  //     level_info: res.level_info,
  //     score: res.score,
  //     qrcodeSrc: data.img,
  //   });
  //   this.setData({ painterInfo: obj, })
  // },
  // onImgOK(e) {
  //   this.setData({ imginfo: e.detail, modalVisible: true })
  // },
  // onClickHide() {
  //   this.setData({ modalVisible: false });
  //   this.back()
  // },
  // onClickShow() {
  //   this.setData({ modalVisible: true });
  // },
  // toSavePic() {
  //   wx.saveImageToPhotosAlbum({
  //     filePath: this.data.imginfo.path,
  //     success: () => {
  //       this.setData({ modalVisible: false })
  //       wx.showToast({
  //         title: '保存成功',
  //         icon: 'success'
  //       });
  //     },
  //     fail: (err) => {
  //       // if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
  //       //   // 用户拒绝了授权，可以提示用户去设置页面开启权限
  //       wx.showModal({
  //         title: '提示',
  //         content: '需要您授权保存相册',
  //         showCancel: false,
  //         success(modalSuccess) {
  //           if (modalSuccess.confirm) {
  //             wx.openSetting({
  //               success(settingdata) {
  //                 if (settingdata.authSetting['scope.writePhotosAlbum']) {
  //                   // 授权成功，可以再次尝试保存图片
  //                 } else {
  //                   // 授权失败，无法保存图片
  //                 }
  //               }
  //             });
  //           }
  //         }
  //       });
  //       // }
  //     }
  //   });
  // },
})
